package com.liuyucheng.idea_springboot.rabbitmq;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

/**
 * RabbitMQ示例
 *
 * @author LiuYuCheng
 * @date 2025年02月11日 10:03
 */
@Slf4j
@Configuration
public class RabbitMqDemo {

    // 定义队列名称
    public static final String QUEUE_NAME = "demo.queue";
    // 定义交换机名称
    public static final String EXCHANGE_NAME = "demo.exchange";
    // 定义路由键
    public static final String ROUTING_KEY = "demo.routing.key";

    /**
     * 声明直连交换机
     */
    @Bean
    public DirectExchange demoExchange() {
        return new DirectExchange(EXCHANGE_NAME);
    }

    /**
     * 声明队列
     */
    @Bean
    public Queue demoQueue() {
        return new Queue(QUEUE_NAME,true);
    }

    /**
     * 绑定队列和交换机
     */
    @Bean
    public Binding bindingDemoQueue() {
        return BindingBuilder.bind(demoQueue())
                .to(demoExchange())
                .with(ROUTING_KEY);
    }
}

/**
 * 消息生产者
 */
@Slf4j
@Component
class MessageProducer {
    
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 发送消息
     * @param message 消息内容
     */
    public void sendMessage(String message) {
        log.info("发送消息: {}", message);
        rabbitTemplate.convertAndSend(RabbitMqDemo.EXCHANGE_NAME, RabbitMqDemo.ROUTING_KEY, message);
    }
}

/**
 * 消息消费者
 */
@Slf4j
@Component
class MessageConsumer {

    /**
     * 监听队列接收消息
     * @param message 消息内容
     */
    @RabbitListener(queues = RabbitMqDemo.QUEUE_NAME)
    public void receiveMessage(String message) {
        log.info("接收到消息: {}", message);
    }
}
